const app = getApp()
const api = require('../../utils/api.js')
const mockData = require('../../utils/data.js')

const PLACEHOLDER_IMAGE = 'https://images.unsplash.com/photo-1523875194681-bedd468c58bf?w=800&h=600&fit=crop'
const USE_MOCK = false // 改为false，使用真实数据库数据

function normalizeProduct(item = {}) {
  if (!item) {
    return null
  }

  const priceValue = item.marketPrice != null ? item.marketPrice : item.price
  const price = priceValue != null && priceValue !== ''
    ? Number(priceValue).toFixed(2)
    : '--'

  const originalPriceValue = item.originalPrice != null ? item.originalPrice : ''
  const onlineDateSource = item.onlineAt || item.earliestDate || ''
  const onlineDate = typeof onlineDateSource === 'string'
    ? onlineDateSource.split(' ')[0]
    : ''

  // 确保id字段正确映射（数据库返回的是productId，需要映射到id）
  const productId = item.productId != null ? item.productId : item.id

  return {
    id: productId,
    title: item.productName || item.title || '',
    location: item.city || item.destination || item.location || '',
    image: item.image || PLACEHOLDER_IMAGE,
    rating: item.rating != null ? Number(item.rating).toFixed(1) : '0.0',
    reviewCount: item.reviewCount != null ? item.reviewCount : 0,
    sales: item.salesCount != null ? item.salesCount : (item.sales != null ? item.sales : 0),
    price,
    originalPrice: originalPriceValue,
    earliestDate: onlineDate,
    productType: item.productType || 'normal',
    date: item.date || ''
  }
}

// 标准化banner数据，将bannerId映射为id
function normalizeBanner(item = {}) {
  if (!item) {
    return null
  }
  return {
    id: item.bannerId != null ? item.bannerId : item.id,
    image: item.image || PLACEHOLDER_IMAGE,
    linkUrl: item.linkUrl || ''
  }
}

// 标准化目的地数据，将destinationId映射为id
function normalizeDestination(item = {}) {
  if (!item) {
    return null
  }
  return {
    id: item.destinationId != null ? item.destinationId : item.id,
    name: item.name || '',
    image: item.image || PLACEHOLDER_IMAGE
  }
}

Page({
  data: {
    banners: [],
    hotDestinations: [],
    browsingHistory: [],
    hotProducts: [],
    recommendedProducts: [],
    loading: false
  },
  
  onLoad() {
    this.loadData()
    this.updateBrowsingHistory()
  },
  
  onShow() {
    this.updateBrowsingHistory()
  },
  
  onPullDownRefresh() {
    this.clearBrowsingHistory()
    this.loadData().finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  updateBrowsingHistory() {
    const history = (app.globalData.browsingHistory || []).map(normalizeProduct).filter(Boolean)
    this.setData({
      browsingHistory: history.slice(0, 5)
    })
  },

  clearBrowsingHistory() {
    app.globalData.browsingHistory = []
    wx.removeStorageSync('browsingHistory')
    this.setData({ browsingHistory: [] })
  },

  loadData() {
    this.setData({ loading: true })
    
    // 本地数据模式：不发任何网络请求，避免控制台 GET 报错
    if (USE_MOCK) {
      const normalizedProducts = (mockData.products || []).map(normalizeProduct).filter(Boolean)
      const normalizedBanners = (mockData.banners || []).map(normalizeBanner).filter(Boolean)
      const normalizedDestinations = (mockData.hotDestinations || []).map(normalizeDestination).filter(Boolean)
      // 热门产品：取前5条数据（按id排序）
      const hotProducts = normalizedProducts.slice(0, 5)
      this.setData({ 
        banners: normalizedBanners.length > 0 ? normalizedBanners : mockData.banners || [],
        hotDestinations: normalizedDestinations.slice(0, 6),
        hotProducts: hotProducts,
        recommendedProducts: normalizedProducts,
        loading: false
      })
      return Promise.resolve()
    }

    const bannerPromise = api.getBanners()
      .then(banners => {
        console.log('获取轮播图成功:', banners)
        const normalizedBanners = (banners || []).map(normalizeBanner).filter(Boolean)
        // 如果数据库没有轮播图，使用mock数据
        return normalizedBanners.length > 0 ? normalizedBanners : (mockData.banners || []).map(normalizeBanner).filter(Boolean)
      })
      .catch(err => {
        console.error('获取轮播图失败:', err)
        return (mockData.banners || []).map(normalizeBanner).filter(Boolean)
      })

    // 获取热门产品（前5条，按id排序）
    const hotProductPromise = api.getHotProducts()
      .then(hotProducts => {
        console.log('获取热门产品成功:', hotProducts)
        return hotProducts || []
      })
      .catch(err => {
        console.error('获取热门产品失败:', err)
        // 降级：如果热门产品接口失败，使用普通产品列表的前5条
        return api.getProducts({ status: 3 }).then(products => {
          console.log('降级使用产品列表:', products)
          return (products || []).slice(0, 5)
      }).catch(() => {
          console.log('使用mock数据')
          return (mockData.products || []).slice(0, 5)
        })
      })

    const productPromise = api.getProducts({ status: 3 }).catch(() => {
      return mockData.products || []
    })

    const normalizedMockDestinations = (mockData.hotDestinations || []).map(normalizeDestination).filter(Boolean)

    return Promise.all([bannerPromise, hotProductPromise, productPromise])
      .then(([banners, hotProducts, products]) => {
        console.log('所有数据加载完成')
        console.log('轮播图数据:', banners)
        console.log('热门产品数据:', hotProducts)
        const normalizedBanners = Array.isArray(banners) ? banners : []
        const normalizedHotProducts = (hotProducts || []).map(normalizeProduct).filter(Boolean)
        console.log('标准化后的热门产品:', normalizedHotProducts)
        const normalizedProducts = (products || []).map(normalizeProduct).filter(Boolean)
      this.setData({ 
          banners: normalizedBanners.length > 0 ? normalizedBanners : (mockData.banners || []).map(normalizeBanner).filter(Boolean),
          hotDestinations: normalizedMockDestinations.slice(0, 6),
          hotProducts: normalizedHotProducts.slice(0, 5), // 确保最多5条
          recommendedProducts: normalizedProducts,
        loading: false
      })
      })
      .catch(() => {
        const fallbackProducts = (mockData.products || []).map(normalizeProduct).filter(Boolean)
        const fallbackHotProducts = fallbackProducts.slice(0, 5)
        const fallbackBanners = (mockData.banners || []).map(normalizeBanner).filter(Boolean)
        const fallbackDestinations = (mockData.hotDestinations || []).map(normalizeDestination).filter(Boolean)
      this.setData({ 
          banners: fallbackBanners,
          hotDestinations: fallbackDestinations.slice(0, 6),
          hotProducts: fallbackHotProducts,
          recommendedProducts: fallbackProducts,
        loading: false
      })
    })
  },
  
  // 搜索
  onSearchTap() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },
  
  // 消息
  onMessageTap() {
    wx.showToast({
      title: '消息功能',
      icon: 'none'
    })
  },
  
  // 跳转到秒杀
  goToFlashSale() {
    wx.navigateTo({
      url: '/pages/product-list/product-list?type=flash-sale'
    })
  },
  
  // 跳转到拼团
  goToGroupBuy() {
    wx.navigateTo({
      url: '/pages/product-list/product-list?type=group-buy'
    })
  },
  
  // 跳转到砍价
  goToBargain() {
    wx.navigateTo({
      url: '/pages/product-list/product-list?type=bargain'
    })
  },
  
  // 跳转到当季热门
  goToSeasonalHot() {
    wx.navigateTo({
      url: '/pages/product-list/product-list?type=seasonal-hot'
    })
  },
  
  // 跳转到目的地列表
  goToDestinationList() {
    wx.switchTab({
      url: '/pages/destination/destination'
    })
  },
  
  // 跳转到目的地商品列表
  goToDestination(e) {
    const cityName = e.currentTarget.dataset.name || ''
    if (!cityName) {
      wx.showToast({
        title: '城市信息错误',
        icon: 'none'
      })
      return
    }
    // 跳转到商品列表页面，传递城市名称作为筛选条件
    wx.navigateTo({
      url: `/pages/product-list/product-list?city=${encodeURIComponent(cityName)}`
    })
  },
  
  // 跳转到产品详情
  goToProductDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${id}`
    })
  },
  
  // 点击轮播图
  onBannerTap(e) {
    const linkUrl = e.currentTarget.dataset.url
    if (linkUrl) {
      // 如果是内部链接，使用navigateTo；如果是外部链接，可以打开webview
      if (linkUrl.startsWith('/')) {
        wx.navigateTo({
          url: linkUrl
        })
      } else {
        wx.showToast({
          title: '外部链接暂不支持',
          icon: 'none'
        })
      }
    }
  }
})

